import React, { useEffect, useState, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { message } from 'antd';
import { getAuthAxios } from '../lib/authAxios.js';

// 主组件
const App = () => {
  const myAxios = getAuthAxios();
  const [iframeEl, setIframeEl] = useState(null);
  const [isEditCheck, setIsEditCheck] = useState(false);
  const highlightItem = useRef(null);
  let tabName = '现场勘查';
  let subTabName = '';
  let formDomItem = {};
  var formItemList;
  var xwqyWarningObj;

  useEffect(() => {
    function onGlobalVarChange(e) {
      if ('上门服务' == window.getMyGlobalVar('activeTabName')) {
        init();
      }
    }
    window.addEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);
    return () => window.removeEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);
  }, []);
  function init() {
    const mainBox = document.querySelector('.main-container-view');
    // const iframeDom = iframe.contentDocument || iframe.contentWindow.document
    observeChanges(mainBox, iFdom => {
      const iframeDomList = document.querySelectorAll('iframe');
      iframeDomList.forEach((item, index) => {
        const computedStyle = window.getComputedStyle(item);
        const displayValue = computedStyle.display;
        if (displayValue == 'block' && index > 1) {
          item.onload = () => {
            const iframeDom = item.contentDocument || item.contentWindow.document;
            observeSave(iframeDom);
            observeChanges(
              iframeDom,
              iframe => {
                highlightItem.current = iframeDom.querySelectorAll('.is-required>label');
                setTimeout(() => {
                  if (highlightItem) highlightItem.current.forEach(i => (i.style.backgroundColor = 'rgb(252,241,118)'));
                }, 100);
                //获取最上方tab信息
                const requireList = iframeDom.querySelectorAll('.card-cell_left');
                //判断tab信息中的用电户分类是否为低压非居民
                requireList.forEach(item => {
                  const textArr = item.textContent.split(' ');
                  if (textArr[1].includes('用电户分类') && textArr[2] == '低压非居民') {
                    //用来判断页面是否稳定，是否是低压非居民页面，如果是的话执行逻辑(监听会一直执行，判断只要执行一次)
                    if (!iframeEl) setIframeEl(iframeDom);
                  }
                });
              },
              { first: false }
            );
          };
        }
      });
    });
  }
  useEffect(() => {
    xwqyWarningObj = window.getMyGlobalVar('warningObj');
    console.log(xwqyWarningObj, '=======');
    function onGlobalVarChange(e) {
      if ('上门服务' == window.getMyGlobalVar('activeTabName')) {
        init();
      }
      xwqyWarningObj = window.getMyGlobalVar('warningObj');
    }
    window.addEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);

    if (iframeEl) {
      const formItem = iframeEl.querySelectorAll('.el-form-item');
      const tabsDom = iframeEl.querySelector('.nav-scroll-wrap');
      const tabsEls = iframeEl.querySelector('.nav-scroll-wrap>div');

      //获取监听tabs,判断在哪个标签执行哪个逻辑
      observeChanges(
        tabsEls,
        el => {
          tabsEls.children.forEach(item => {
            if (item.classList.contains('active')) {
              tabName = item.textContent;
            }
          });
          if (!tabName) return;
          console.log('tabsEls监听中', tabName);
          setTimeout(() => {
            const subTabsDom = iframeEl.querySelector('.card-first-box_yx');
            // console.log(subTabsDom, '================subTabsDomsubTabsDomsubTabsDomsubTabsDom==========')
            observeChanges(
              subTabsDom,
              item => {
                console.log('subTabsDom监听中');
                // console.log('treeContainer监听中')
                formItemList = [];
                formItemList = iframeEl.querySelectorAll('.el-form-item');
              },
              { attributes: true }
            );
          }, 1500);
        },
        { attributes: true }
      );

      setTimeout(() => {
        //延迟1s后出现，避免数据没获取到但是用户点击核验行为
        const btn = document.createElement('button');
        btn.style.position = 'absolute';
        btn.style.top = '0';
        btn.style.left = '550px';
        btn.style.zIndex = '999';
        btn.style.backgroundColor = '#4caf50';
        btn.style.color = 'white';
        btn.style.border = 'none';
        btn.style.padding = '10px 20px';
        btn.style.cursor = 'pointer';
        btn.textContent = '一键复核';
        btn.style.borderRadius = '5px';
        btn.opacity = '0.5';
        btn.id = 'checksmfw-btn';
        btn.addEventListener('click', () => {
          //添加点击事件，通过判断tabName执行不同标签下的逻辑
          /**
           * 现场勘察逻辑：
           * 1.用户名称带“公司”、“合作社”，或户名长度大于等于4个汉字为三零小微企业，不是的话预警
           * 2.【充电桩用户标志】或者【是否集中电动自行车充电】二者有一个选择【是】则为三零非小微，不是的话预警
           * 3.【小微非三零】，山东地区没有
           * 4.其余为非三零非小微。以上核查有误则在当前页面高亮显示
           */
          console.log(tabName, '================================================tabName===========================================');
          if (tabName == '现场勘查') {
            xwqyWarningObj.fields = '是否三零小微企业';
            console.log(xwqyWarningObj, 'dwarningObjwarningObjwarningObjwarningObjwarningObj');
            //验证条件1
            if (
              (formDomItem['用电户名称'].value.includes('公司') ||
                formDomItem['用电户名称'].value.includes('合作社') ||
                formDomItem['用电户名称'].value.length >= 4) &&
              formDomItem['是否三零小微企业'].value !== '三零小微'
            ) {
              formDomItem['是否三零小微企业'].dom.style.backgroundColor = '#ecf500';
              saveWarningData(xwqyWarningObj);
              message.warning('是否三零小微企业校验不通过');
            }
            //验证条件2
            else if (
              (formDomItem['是否电动汽车充换电设施'].value == '是' || formDomItem['是否集中电动自行车充电'].value == '是') &&
              formDomItem['是否三零小微企业'].value !== '三零非小微'
            ) {
              formDomItem['是否三零小微企业'].dom.style.backgroundColor = '#ecf500';
              saveWarningData(xwqyWarningObj);
              message.warning('是否三零小微企业校验不通过');
            }
            //验证条件3
            else if (formDomItem['用户地址'].value.includes('山东') && formDomItem['是否三零小微企业'].value === '小微非三零') {
              formDomItem['是否三零小微企业'].dom.style.backgroundColor = '#ecf500';
              saveWarningData(xwqyWarningObj);
              message.warning('是否三零小微企业校验不通过');
            } else {
              saveNewData(xwqyWarningObj);
              message.success('是否三零小微企业校验通过');
            }
          }
          if (tabName == '方案拟定') {
            let check = '不考核';
            if (formDomItem['核定合计用电容量'].value >= 100 && formDomItem['定价策略类型'].value === '单一制') {
              check = '标准考核';
            }

            formItemList.forEach(i => {
              //  功率因数考核
              if ('功率因数考核方式' == i.title) {
                let glys = i.querySelector('div > div > input').value;
                console.log('glys', glys);
                if (!glys) {
                  return;
                }
                if (glys == check) {
                  console.log('校验通过');
                  message.success('功率因数考核方式校验通过');
                  xwqyWarningObj.fields = '功率因数考核方式';
                  saveNewData(xwqyWarningObj);
                } else {
                  console.log('不通过');
                  xwqyWarningObj.fields = '功率因数考核方式';
                  saveWarningData(xwqyWarningObj);
                  const inputDOM = i.querySelector('input');
                  inputDOM.style.backgroundColor = 'red';
                  message.warning('功率因数考核方式校验不通过');
                }
              }
              //电价行业类别  行业分类  是否电动汽车充换电设施
              if (formDomItem['是否电动汽车充换电设施'].value == '是') {
                let check = formDomItem['行业分类'].value;
                if ('电价行业类别' == i.title) {
                  let hyfl = i.querySelector('div > div > input').value;
                  console.log('hyfl', hyfl);
                  if (!hyfl) {
                    return;
                  }
                  if (hyfl == check) {
                    console.log('校验通过');
                    xwqyWarningObj.fields = '电价行业类别';
                    saveNewData(xwqyWarningObj);
                    message.success('电价行业类别校验通过');
                  } else {
                    console.log('不通过');
                    const inputDOM = i.querySelector('input');
                    inputDOM.style.backgroundColor = 'red';
                    message.warning('电价行业类别校验不通过');
                    xwqyWarningObj.fields = '电价行业类别';
                    saveWarningData(xwqyWarningObj);
                  }
                }
              }
            });
          }
        });
        tabsDom.appendChild(btn);
      }, 1500);
      //摘取【现场勘察】表单字段（有异步铺设字段，需要延迟获取）
      setTimeout(() => {
        let formData = {};
        formItem.forEach(item => {
          if (item.querySelector('input')) {
            formData[item.children[0].textContent] = {
              value: item.querySelector('input').value,
              dom: item.querySelector('input')
            };
          }
        });
        formDomItem = formData;
      }, 1000);
    }
  }, [iframeEl, highlightItem, xwqyWarningObj]);

  const saveWarningData = warningData => {
    console.log('warningdata', warningData);
    myAxios
      .post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcRemindMsg/addBatch', [warningData])
      .then(response => {
        console.log('数据已成功发送:', response.data);
      })
      .catch(error => {
        console.error('发送数据失败:', error);
      });
  };
  const observeSave = dom => {
    dom.addEventListener(
      'click',
      function (e) {
        const btn = e.target;
        if (btn && (btn.textContent == '保存' || btn.textContent == '发送')) {
          setIsEditCheck(true);
          const child = dom.querySelector('#checksmfw-btn');
          child && child.click();
        }
      },
      true
    );
  };
  /**
   * 更新新数据
   * 点击保存、发送
   */
  const saveNewData = newData => {
    if (!isEditCheck) {
      console.log('没电点击保存、发送');
      return;
    }
    console.log('newData', newData);
    console.log('已经点击了保存、发送');
    myAxios
      .post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcRemindMsg/addBatch', [newData])
      .then(response => {
        console.log('新数据已成功发送:', response.data);
      })
      .catch(error => {
        console.error('发送新数据失败:', error);
      });
  };
  return () => window.removeEventListener('MY_GLOBAL_VAR_CHANGE', onGlobalVarChange);
};

// 渲染函数
const init = () => {
  const container = document.createElement('div');
  container.style.fontSize = '14px';
  document.body.appendChild(container);
  const root = createRoot(container);
  root.render(<App />);
};

// 执行初始化
init();
